package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BasePageInfo;
import com.cskaoyan.bean.MarketLog;
import com.cskaoyan.bean.MarketLogExample;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.mapper.MarketLogMapper;
import com.cskaoyan.service.admin.MarketLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Bowen Deng
 * @since 2022/06/26 20:40
 */
@Service
public class MarketLogServiceImpl implements MarketLogService {

    @Autowired
    MarketLogMapper marketLogMapper;

    /**
     * 利用给的example进行模糊查询，然后封装进commondata
     *
     * 此处的name对应的是数据库表里的admin
     * @param name
     * @param info
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.MarketLog>
     * @author Bowen Deng
     * @since 2022/06/26 8:48 下午
     */
    @Override
    public CommonData<MarketLog> list(String name, BasePageInfo info) {
        //开启分页查询
        PageHelper.startPage(info.getPage(), info.getLimit());
        //利用老师给好的BO去查询，Example就是数据库查询的时候用到的参数
        MarketLogExample marketLogExample = new MarketLogExample();
        //criteria标准，就是要根据什么进行查询，比如在这里根据Admin的name进行模糊查询
        MarketLogExample.Criteria criteria = marketLogExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        //判断name是不是空，如果是空的话就不需要模糊查询了，如果不是空，需要拼接参数进行模糊查询
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name.trim() + "%";
            //这一步就是告诉criteria，你要用Admin进行模糊查询了
            criteria.andAdminLike(name);
        }
        marketLogExample.setOrderByClause("id desc");
        //查询的时候要调用写好的方法，selectByExample，然后传入你前面new的并且声明了criteria的对象
        List<MarketLog> marketLogs = marketLogMapper.selectByExample(marketLogExample);
        //利用pagehelper插件去封装查询的结果
        PageInfo<MarketLog> marketLogPageInfo = new PageInfo<>(marketLogs);
        //封装到commondata
        CommonData data = CommonData.data(marketLogPageInfo);
        return data;
    }

    /**
     * 在这里直接调用mapper里的方法去增加一个新的日志
     *
     * @param marketLog
     * @return
     */
    @Override
    public Integer addLog(MarketLog marketLog) {
        int affectedRows = marketLogMapper.insert(marketLog);
        return affectedRows;
    }
}
